package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        if (dto.getCommentId()==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"评论id为空");
        }
        if (dto.getSize()==null||dto.getSize()==0){
            dto.setSize(10);
        }
        if (dto.getMinDate()==null){
            dto.setMinDate(new Date());
        }
        Query query = Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate())
        );
        Sort sort = Sort.by(Sort.Direction.DESC,"createdTime");
        query.with(sort).limit(dto.getSize());// 排序
        List<ApCommentRepay> commentList = mongoTemplate.find(query, ApCommentRepay.class);
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.okResult(commentList);
        }

        List<ApCommentRepayVO> apCommentRepayVOS = new ArrayList<>();
        for (ApCommentRepay comment : commentList) {

            Query queryList = Query.query(Criteria
                    .where("commentId").is(comment.getId())
                    .and("authorId").is(user.getId())
            );
            List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(queryList, ApCommentRepayLike.class);
            ApCommentRepayVO apCommentVo = new ApCommentRepayVO();
//            BeanUtils.copyProperties(apCommentVo,comment);
            BeanUtils.copyProperties(comment,apCommentVo);
            if (apCommentRepayLikes.size()!=0){
                apCommentVo.setOperation((short)0);
            }
            apCommentRepayVOS.add(apCommentVo);
        }
        System.out.println(apCommentRepayVOS);
        return ResponseResult.okResult(apCommentRepayVOS);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请先登录");
        }
        if (dto.getCommentId() == null || dto.getContent() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论id或者评论内容不能为空");
        }
        if (dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能大于140个字符");
        }
        boolean scanText = handleTextScan(dto.getContent());
        ResponseResult<ApUser> result = userFeign.findUserById(user.getId());
        ApUser data = result.getData();

        if (!scanText) {
            // 返回false代表审核不成功   结束处理
            log.info("文章审核未通过，原因: 内容中包含违规词汇");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "内容中包含违规词汇");
        }else{
            ApCommentRepay apLikesBehavior2 = ApCommentRepay.builder()
                    .authorId(user.getId())
                    .authorName(data.getName())
                    .createdTime(new Date())
                    .content(dto.getContent())
                    .commentId(dto.getCommentId())
                    .likes(0)
                    .build();
            ApCommentRepay saveResult = mongoTemplate.insert(apLikesBehavior2);

            Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            ApComment comment = mongoTemplate.findOne(query, ApComment.class);
            Update update = new Update();

            update.set("reply", comment.getReply()+1);
            UpdateResult updateResult = mongoTemplate.updateMulti(query, update, ApComment.class);
            System.out.println(updateResult);


            return ResponseResult.okResult(saveResult);
        }

    }
    @Autowired
    UserFeign userFeign;
    @Autowired
    private GreenScan greenScan;

    private boolean handleTextScan(String content) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    // 失败
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
                    break;
                case "review":
                    // 人工
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
                    break;
                case "pass":
                    // 成功
                    flag = true;
                    break;
                default:
                    // 人工
                    CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "评论中含有违规信息");
        }
        return flag;
    }
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {

        if (dto.getCommentRepayId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论id不能为空");
        }
        Query query = Query.query(Criteria.where("_id").is(dto.getCommentRepayId()));
        ApCommentRepay apComment = mongoTemplate.findOne(query, ApCommentRepay.class);
        log.info("查询评论信息是否存在" + apComment);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不存在");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请先登录");
        }
        Query queryLike = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentLike = mongoTemplate.findOne(queryLike, ApCommentRepayLike.class);
        if (dto.getOperation() == 0) {
            if (apCommentLike != null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "您已点过赞，请勿重复点赞");
            }
            ApCommentRepayLike apLikesBehavior2 = ApCommentRepayLike.builder()
                    .authorId(user.getId())
                    .commentRepayId(dto.getCommentRepayId())
                    .operation((short) 0)
                    .build();
            ApCommentRepayLike saveResult = mongoTemplate.insert(apLikesBehavior2);
            //修改点赞数量
            Update update = new Update();
            update.set("likes", apComment.getLikes() + 1).set("updatedTime", new Date());
            UpdateResult updateResult = mongoTemplate.updateMulti(query, update, ApCommentRepay.class);
            System.out.println(updateResult);
            Map map = new HashMap();
            map.put("authorId", user.getId());
            map.put("commentRepayId", dto.getCommentRepayId());
            map.put("operation", (short) 0);
            map.put("likes", apComment.getLikes() + 1);
            return ResponseResult.okResult(map);
        } else if (dto.getOperation() == 1) {
            if (apCommentLike != null) {
                DeleteResult removeResult = mongoTemplate.remove(queryLike, ApCommentRepayLike.class);
                log.info("用户取消点赞成功" + removeResult);
                Update update = new Update();
                if (apComment.getLikes() > 0) {
                    update.set("likes", apComment.getLikes() - 1).set("updatedTime", new Date());
                    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, ApCommentRepay.class);

                return ResponseResult.okResult(updateResult);
                }
            }
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "点赞不存在");
        }
        return null;
    }
}
